﻿<%@ WebHandler Language="C#" Class="Common" %>

using System;
using System.Web;

public class Common : AjaxHandlerBase
{
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strop = context.Request["op"];

        try
        {
            switch (strop.ToLower())
            {
                case "getlastyearcombo":
                    GetLastYear(context);
                    break;
                case "getdatadictionary":
                    GetDataDictionary(context);
                    break;
                case "getcombo":
                    GetCombo(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:{{items:[]}}}}", ex.Message));
        }
    }

    /// <summary>
    /// 获取常用下拉框数据，包括数据字典和城市
    /// 
    /// 不存在全部都不回去的情况，因为前段方法会执行相应的判断
    /// </summary>
    /// <param name="context"></param>
    private void GetCombo(HttpContext context)
    {
        if (string.IsNullOrEmpty(context.Request["datakeylist"]) && context.Request["getcity"].ToLower() == "false")
        {
            context.Response.Write("{success:1,msg:'',data:''}");
        }
        
        if (string.IsNullOrEmpty(context.Request["datakeylist"]))//只获取城市
        {
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{city:{0}}}}}", GetCitys(context)));
        }
        else if (context.Request["getcity"].ToLower() == "false")//只获取数据字典
        {
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{dictionary:{0}}}}}", GetDataDictionary(context)));            
        }
        else//全部获取
        {
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{city:{0},dictionary:{1}}}}}", GetCitys(context), GetDataDictionary(context)));
        }
    }

    /// <summary>
    /// 获取所有城市列表
    /// </summary>
    /// <returns></returns>
    private string GetCitys(HttpContext context)
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo> citylist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            string permitCode = Chenxin.Lib.Utility.Constants.Permit_SelectAllCity;
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            if (CurrentUserInfo.ContainsPermit(permitCode))
            {
                //首先从缓存中获取数据
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                citylist = cs.GetList<Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo>(strCacheKey);

                if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
                {
                    citylist = Chenxin.Lib.Hr.DAL.Struct_CityBaseInfo.GetListArray("");

                    cs.Set(strCacheKey, citylist, DateTime.Today.AddDays(1));
                }

                //生成JSON字符串
                foreach (Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo item in citylist)
                {
                    str.Append("{ txt: '" + item.CityName.Trim() + "', val: '" + item.CityId.ToString() + "' },");
                }
                if (str.Length > 0) str.Remove(str.Length - 1, 1);
            }
            else
            {
                str.Append("{ txt: '" + CurrentUserInfo.CityName.Trim() + "', val: '" + CurrentUserInfo.CityId.ToString() + "' }");
            }

            return string.Format("[{0}]", str.ToString());
        }
        catch
        {
            return "";
        }
    }

    /// <summary>
    /// 获取数据字典，根据itemkeylist
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetDataDictionary(HttpContext context)
    {
        if (context.Request["datakeylist"] != null)
        {
            string strWhere = "";
            string datakeylist = context.Request["datakeylist"];
            datakeylist = datakeylist.Replace(",", "','");
            strWhere = string.Format("CompanyId = '{0}' AND ItemKey in ('{1}')", CurrentUserInfo.CompanyId, datakeylist);
            System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary> dicList = null;
            dicList = Chenxin.Lib.House.DAL.DataDictionary.GetListArray(strWhere, "ItemKey asc,ItemIndex desc");

            System.Text.StringBuilder str = new System.Text.StringBuilder();
            str.Append("{");
            string tk = "";
            foreach (Chenxin.Lib.House.Entity.DataDictionary item in dicList)
            {
                if (tk != item.ItemKey)
                {
                    tk = item.ItemKey;
                    if (str.Length > 1)
                    {
                        str.Remove(str.Length - 1, 1);
                        str.Append("],");
                    }
                    str.Append(tk.Replace(".", "") + ":[");
                }

                str.Append("{ txt: '" + item.ItemValue.Trim() + "', val: '" + item.ItemIndex + "',id:'" + item.RecordId + "'},");
            }
            if (str.Length > 1)
            {
                str.Remove(str.Length - 1, 1);
                str.Append("]");
            }
            str.Append("}");
            return str.ToString();
            //context.Response.Write("{success:1,msg:'',data:" + str.ToString() + "}");
        }
        return "";

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    private void GetLastYear(HttpContext context)
    {
        try
        {
            int yearlength = 10;
            if (!string.IsNullOrEmpty(context.Request.Params["yearLength"]))
                int.TryParse(context.Request.Params["yearLength"], out yearlength);

            int year = DateTime.Now.Year;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < yearlength; i++)
            {
                sb.AppendFormat("{{txt:'{0}',val:'{0}'}},", year);
                year = year - 1;
            }
            context.Response.Write(string.Format("{{success:'1',msg:'',data:{{items:[{0}]}}}}",sb.ToString().Substring(0,(sb.ToString().Length-1))));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:{{items:[]}}}}", ex.Message));
        }
    }

}